package org.jetlinks.pro.cassandra.metadata;

import org.hswebframework.ezorm.rdb.executor.DefaultBatchSqlRequest;
import org.hswebframework.ezorm.rdb.metadata.RDBColumnMetadata;
import org.hswebframework.ezorm.rdb.metadata.dialect.DataTypeBuilder;
import org.hswebframework.ezorm.rdb.operator.DatabaseOperator;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.PrepareSqlFragments;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.ddl.CommonAlterTableSqlBuilder;
import org.hswebframework.ezorm.rdb.operator.ddl.TableBuilder;

import static org.hswebframework.ezorm.rdb.operator.builder.fragments.PrepareSqlFragments.of;

/**
 * 对Cassandra ddl 修改表结构的支持,支持添加列,修改列类型,删除列.
 * <br>
 * 暂时不支持更新索引.
 *
 * @author zhouhao
 * @see DatabaseOperator#ddl()
 * @see org.hswebframework.ezorm.rdb.operator.DDLOperator#createOrAlter(String)
 * @see TableBuilder#addColumn()
 * @see TableBuilder#dropColumn(String)
 * @see RDBColumnMetadata
 * @since 1.10
 */
public class CassandraAlterTableSqlBuilder extends CommonAlterTableSqlBuilder {

    @Override
    protected void appendAddColumnCommentSql(DefaultBatchSqlRequest batch, RDBColumnMetadata column) {
        //不支持列注释
    }

    protected PrepareSqlFragments createAlterTable(RDBColumnMetadata column) {
        return of()
            .addSql("ALTER", "TABLE", column.getOwner().getFullName());
    }

    @Override
    protected void appendAddColumnSql(DefaultBatchSqlRequest batch, RDBColumnMetadata column) {
        DataTypeBuilder type = ((DataTypeBuilder) column.getType());
        PrepareSqlFragments fragments = createAlterTable(column);
        //ALTER TABLE {table} ADD {column} {type}
        fragments.addSql("ADD")
                 .addSql(column.getQuoteName())
                 .addSql(type.createColumnDataType(column));

        batch.addBatch(fragments.toRequest());
    }

    @Override
    protected void appendDropColumnSql(DefaultBatchSqlRequest batch, RDBColumnMetadata drop) {
        PrepareSqlFragments fragments = createAlterTable(drop);
        //ALTER TABLE {table} DROP {column}
        fragments.addSql("DROP")
                 .addSql(drop.getQuoteName());

        batch.addBatch(fragments.toRequest());
    }

    @Override
    protected void appendAlterColumnSql(DefaultBatchSqlRequest batch,
                                        RDBColumnMetadata oldColumn,
                                        RDBColumnMetadata newColumn) {
        DataTypeBuilder type = ((DataTypeBuilder) newColumn.getType());
        PrepareSqlFragments fragments = createAlterTable(newColumn);
        // ALTER TABLE {table} ALTER {column} TYPE {type}
        fragments.addSql("ALTER")
                 .addSql(newColumn.getQuoteName())
                 .addSql("TYPE")
                 .addSql(type.createColumnDataType(newColumn));

        batch.addBatch(fragments.toRequest());
    }
}
